<?php
namespace app\api;
use think\Controller;

use app\common\model as M;
class ApiBase extends Controller {
    use \traits\ShotcutControllerTrait;

    protected $platform   = 'mp';
    protected $token      = '';
    protected $sign       = '';
    protected $uid        = 0;
    protected $spread_uid = 0; // 推广会员UID
    protected $spread_suid= 0; // 推广销售经理ID
    protected $mobile     = '';
    protected $userInfo   = [];
    protected $page       = 1;
    protected $limit      = 10;

    const APP_KEY = 'DD1B86F923EAC08615D89B0299089FD4';

    ## 缓存时间
    const CACHE_TIME = 300;

    protected function _initialize()
    {
        parent::_initialize();

        $timestamp = (int)$this->request->get('timestamp');
        //if ( !$timestamp ) $this->returnFail('时间戳参数【timestamp】缺失',403);

        $sign = $this->request->header('sign');
        $this->token = $this->request->header('token');
        ## 校验签名
        if ( !$this->checkSign($sign , $this->request) ) $this->returnFail('签名验证失败',403);

        $this->userInfo = M\User::get_login($this->token);
        if( !empty($this->userInfo) ){
            $this->uid    = $this->userInfo['uid'];
            $this->mobile = $this->userInfo['mobile'] ?? '';
        }

        if ( empty($this->userInfo) ) {
            if ( $this->mustAuthListCheck() ) {
                return $this->returnFail('请登录后再操作',201);
            }
        }

        $page  = $this->request->param('page');
        $limit = $this->request->param('limit');
        if ( $page > 0 ) $this->page = $page;
        if ( $limit > 0 ) $this->limit = $limit;

        $platform = $this->request->param('platform');
        if ( $platform ) $this->platform = $platform;

        $this->spread_suid = $this->request->header('Spreader-Sales-Uid');
        $this->spread_uid  = $this->request->header('Spreader-Uid');
    }

    /***
     * 必须鉴权的方法
     */
    public static function authList()
    {
        return [];
    }

    /**
     * 校验签名
     */
    public function checkSign( $sign , \think\Request $request )
    {
        return true;//sha1(self::APP_KEY . input('timestamp') . $this->token) == $sign;

        $params = [];
        if ( strtoupper($request->method()) === 'GET' ) {
            $params = $request->get();
        }

        if ( strtoupper($request->method()) === 'POST' ) {
            $params = $request->post();
        }

        $params['timestamp'] = $request->get('timestamp');
        ksort($params);


        return sha1(http_build_query($params) . '&app_key=' . self::APP_KEY) == $sign;
    }

    /**
     * 成功输出
     * @param  array   $data [description]
     * @param  integer $code [description]
     * @param  string  $msg  [description]
     * @return [type]        [description]
     */
    public function returnSuccess ( $data = [] , $code = 0, $msg = 'OK' )
    {
        return exit(json_encode([
            'code'  =>  $code,
            'msg'   =>  $msg,
            'data'  =>  $data
        ]));
    }

    /**
     * [returnSuccess description]
     * @param  array   $data [description]
     * @param  integer $code [description]
     * @param  string  $msg  [description]
     * @return [type]        [description]
     */
    public function returnFail ( $error = 'ERROR'  , $code = 500 )
    {
        return exit(json_encode([
            'code'    =>  $code,
            'error'   =>  $error,
            'msg'     =>  $error,
        ]));
    }

    /**
     * 获取列表
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function get_list ()
    {
        $where = $this->request->get();
        $where['page']  = $where['page'] ?? 1;
        $where['limit'] = $where['limit'] ?? 20;
        return $this->returnSuccess($this->model::getList($where));
    }

    public function get_all ()
    {
        $where = $this->request->get();
        return $this->returnSuccess($this->model::getListArr($where));
    }

    /**
     * @Author   FW
     * @DateTime 2021-04-13
     * @Email    123763712@qq.com
     * @param    integer          $id [description]
     */
    public function view( $id )
    {
        $data = $this->model::getOne($id);
        if ( !empty($data) ) {
            return $this->returnSuccess($data);
        }

        return $this->returnFail('无数据');
    }

    /*
     * 检查白名单控制器方法 存在带名单返回 true 不存在则进行登录
     * */
    protected function NoWechantVisitWhite(){
        list($module,$controller,$action,$className)=$this->getCurrentController();
        if(method_exists($className,'WhiteList')){
            $whitelist=$className::WhiteList();
            if(!is_array($whitelist)) return false;
            foreach ($whitelist as $item){
                if(strtolower($module.'\\'.$controller.'\\'.$item)==strtolower($module.'\\'.$controller.'\\'.$action)){
                    return true;
                }
            }
        }
        return false;
    }

    /*
     * 检查黑名单控制器方法 存在带名单返回 true 存在则进行登录
     * */
    protected function mustAuthListCheck(){
        list($module,$controller,$action,$className)=$this->getCurrentController();
        if(method_exists($className,'authList')){
            $blackList=$className::authList();
            if(!is_array($blackList)) return false;
            foreach ($blackList as $item){
                if(strtolower($module.'\\'.$controller.'\\'.$item)==strtolower($module.'\\'.$controller.'\\'.$action)){
                    return true;
                }
            }
        }
        return false;
    }

    /*
     * 获取当前的控制器名,模块名,方法名,类名并返回
     * */
    protected function getCurrentController()
    {
        $module=$this->request->module();
        $controller=$this->request->controller();
        $action=$this->request->action();
        if(strstr($controller,'.'))
            $controllerv1=str_replace('.','\\',$controller);
        else
            $controllerv1=$controller;
        $className='app\\'.$module.'\\controller\\'.$controllerv1;
        return [$module,$controller,$action,$className];
    }

    /**
     * 获取当前登录用户信息
     * @Author   FW
     * @DateTime 2021-05-17
     * @Email    123763712@qq.com
     * @return   array
     */
    protected function get_current_user ()
    {
        return $this->userInfo;
    }
} // Class End